/**
 * 分段专题图
 * 说明：可选择分段算法、分段数目、分段颜色
 */
import sgisRegionBase from '../../sfgis.region.base';
import sgisLayerBase from '../../sfgis.layer.base';
import sgisSpatialQuery from "../../sfgis.spatial.query";
import dataAnalysis from "../../sfgis.data.analysis";
import styleModify from "./echarts.stylemodify"; // 为图层设置透明度，可见性，zIndex而设置
import store from "../../../../pages/macro/store";
export default {
  layerNum: 0,
  // 默认配色方案  默认分为5段
  popup: "",
  themeLayer: "",
  themeLayerInfo: {},
  themeField: "POP_DENSITY99",
  featureData: {},
  map: "",
  styleGroups: [],
  segment_values: "",
  colors: [
    ["FEE5D9", "FCAE91", "FB6A4A", "DE2D26", "A50F15"],
    ["FEEDDE", "FDBE85", "FD8D3C", "E6550D", "A63603"],
    ["FFFFCC", "C2E699", "78C679", "31A354", "006837"],
    ["FFFFCC", "A1DAB4", "41B6C4", "2C7FB8", "253494"],
    ["F0F9E8", "BAE4BC", "7BCCC4", "43A2CA", "0868AC"],
    ["EDF8FB", "B2E2E2", "66C2A4", "2CA25F", "006D2C"],
    ["F6EFF7", "BDC9E1", "67A9CF", "1C9099", "016C59"],
    ["F1EEF6", "BDC9E1", "74A9CF", "2B8CBE", "045A8D"],
    ["EDF8FB", "B3CDE3", "8C96C6", "8856A7", "810F7C"]
  ],
  callbackLayer: '',
  currentHighLightRegion:'',
  /**
   * {
        id:"",  // 图层id
        name:"",   // 图层名称
        datas:[    //数据支持多年数据展示
          {
            segment_values:[],  // 图层分段值
            values:[{"regioncode":"","rname":"","regiontype":"","value":"",},{}]
          }  // 数值信息
        ]
   * }
   * @param {Object} map 地图对象
   * @param {Object} data  出图参数
   *  @param {Object} callbackLayer  回调函数
   */
  createLayer(map, data, callbackLayer) {
    let that = this;
    this.map = map;
    this.segment_values = data.datas[0].segment_values
    this.callbackLayer = callbackLayer;
    let popup;
    //用所有年份的值去计算分段
    let segment_values_temp = dataAnalysis.themerange.getSegmentByDataArr(
      data.datas[0].all_segment_values,
      5
    );
    let themeLayerColor = this.getStyleGroups(segment_values_temp);
    this.styleGroups = themeLayerColor;
    let currentCode = "";
    let themeLayer = new mapboxgl.supermap.DeckglLayer('polygon-layer', {
      data: [],
      props: {
        stroked: true,
        extruded: true,
        filled: true,
        opacity: 1,
        autoHighlight: true,
        highlightColor: [255, 255, 0, 255],
        lightSettings: {
          lightsPosition: [-73, 40, 5000, -74, 41, 5000],
          ambientRatio: 0.2,
          diffuseRatio: 0.5,
          specularRatio: 0.3,
          lightsStrength: [1.0, 0.0, 2.0, 0.0],
          numberOfLights: 2
        },
        onClick: function (feature) {
          console.log(feature)
        },
        onHover: function (feature) {
          if (!popup) {
            popup = new mapboxgl.Popup({
              anchor: 'bottom',
              closeButton: false,
              offset: {
                'bottom': [0, -10],
              }
            });
          }
          if (!feature.object) {
            popup.remove();
            EventBus.$emit("offChart-action", { regionCode: currentCode });
            EventBus.$emit("table-heighLightOff", { regionCode: currentCode });
            // console.log('删除')
            // themeLayer.removeCurrentData();
            return;
          }
          //+" "+feature.lngLat
          currentCode = feature.object.properties.QH_CODE
          // if(that.currentHighLightRegion !=currentCode){
          //   that.currentHighLightRegion = currentCode;
          //   EventBus.$emit("onLayer-action", { regionCode:currentCode });
          // }

          let innerHtml = `<div><span>区划名称：${feature.object.properties.QH_NAME}</span></br><span>${store.state.macro.currentIdenName['themerange']}：${feature.object.properties.value}</span></div>`
          popup.setHTML(innerHtml);
          popup.setLngLat(map.unproject([feature.x, feature.y]));
          popup.addTo(map);
          EventBus.$emit("onChart-action", { regionCode: feature.object.properties.QH_CODE });
          EventBus.$emit("table-actiontrigger", {
            regionCode: feature.object.properties.QH_CODE
          });
        }
      }
    });
    themeLayer.options = {
      ...themeLayer.options,
      ...this
    }; // 自定义设置颜色时用到参数设置
    themeLayer.styleGroups = themeLayerColor;
    themeLayer.options.styleGroups = themeLayerColor
    var maxSize = 100,minSize = 20;
    let regionLevel = sgisRegionBase.regionInfos.getCurrentRegionLevel();
    if( regionLevel >= 5 ){
       maxSize = 50;
       minSize = 10;
    }
    let arrmaxdata = Math.max(...this.segment_values);
    let arrmindata = Math.min(...this.segment_values);
    let datajg = (arrmaxdata - arrmindata)/(maxSize-minSize);
    themeLayer.callback = {
      getPolygon: function (feature) {
        if (!feature.geometry || !feature.geometry.coordinates) {
          return [0, 0];
        }
        feature.properties["maxSize"] = maxSize;
        feature.properties["minSize"] = minSize;
        feature.properties["arrmindata"] = arrmindata;
        feature.properties["datajg"] = datajg;
        feature.properties["regionlevel"] = regionLevel;
        return feature.geometry.coordinates[0];
      },  
      getElevation: function (d) {
        let value = Number(d.properties.value);
        if(value==0){//值为0不再绘制
          return;
        }
        let arrmindata = Number(d.properties["arrmindata"]);
        let datajg = Number(d.properties["datajg"]);
        let minSize = Number(d.properties["minSize"]);
        let maxSize = Number(d.properties["maxSize"]);
        let level = sgisRegionBase.regionInfos.getCurrentRegionLevel();
        let size = 100;
        if(datajg!=0){
          size = Math.round((eval((value-arrmindata)/datajg)+minSize)||maxSize);
        }
        let escale = 750;
        if(level === 2 ){//省
          // escale  = 300;
          if(datajg === 0){
            return 100 * escale;
          }
        }else if(level === 3){//市
          // escale  = 200;
          if(datajg === 0){
            return 100 * escale;
          }
        }else if(level === 4 ){//区县
          escale  = 200;
          if(datajg === 0){
            return 40 * escale;
          }
        }else if(level === 5){//镇
          escale = 50;
          if(datajg === 0){
            return 10* escale;
          }
        }else if(level >5){
          escale = 15;
          if(datajg === 0){
            return 5 * escale;
          }
        }
        return size * escale;
      },
      getFillColor: (feature) => {
        for (let i = 0; i < themeLayer.options.styleGroups.length; i++) {
          if (feature.properties.value > themeLayer.options.styleGroups[i].start && feature.properties.value <= themeLayer.options.styleGroups[i].end) {
            if (feature.heightColor) {
              return [255, 255, 0, 255]
            }
            return this.hexToRgb(themeLayer.options.styleGroups[i].style.color)
          }
        }

        return this.hexToRgb(themeLayer.options.styleGroups[0].style.color);
      }
    }
    themeLayer.type = "themerange"
    //删除当前高亮图层
    themeLayer.removeCurrentData = function () {
      if (this.layer["props"]) {
        for (let i = 0; i < this.layer.props.data.length; i++) {
          if (this.layer.props.data[i].heightColor) {
            this.layer.props.data.splice(i, 1)
          }
        }
      }
      this.update();
    }
    // 分段风格数组
    themeLayer.styleGroups = themeLayerColor;
    themeLayer.themeLayer = themeLayer

    //设置高亮图层提示
    this.addFeatures(data.datas[0].values, themeLayer, map);
    // map.addLayer(themeLayer.themeLayer)
    let layerid = 'themerange';
    // 用于专题图的值得字段名称
    themeLayer.themeField = "value";
    themeLayer.layerId = layerid;
    // 为themeLayer 注册修改color的方法
    themeLayer.setCustomColor = this.setCustomColor;
    // 将数据绑定到图层，方便刷新图层

    themeLayer.setOpacity = this.setOpacity; // 设置图层透明度
    themeLayer.getStyleGroups = this.getStyleGroups; // 设置图层透明度
    // themeLayer.layerId = layerid;

    // 绑定鼠标进入时间
    // themeLayer.on("mousemove", this.showInfoWin);
    // themeLayer.on("mouseout", this.closeInfoWin);
    themeLayer.setZIndexOffset = this.setZIndexOffset; // 设置图层顺序函数
    // themeLayer.container.style.zIndex = styleModify.curZindex; // 为设置图层顺序调整特意设置
    styleModify.layerOrder[layerid] = styleModify.curZindex;
    themeLayer.options.currdata = data.datas[0]; // 当前数据
    styleModify.curZindex -= 1;
    themeLayer.setVisible = this.setVisible; // 设置图层可见性
    // 保存一下图层信息
    this.themeLayerInfo = {
      // 要保证此id和themeLayer的option中的id一致，此处只有根据元素id获得layer
      layerId: 'themerange',
      name: data.name,
      show: data.showThumbnails !== false,
      type: 'themerange',
      html: this.calgraph('themerange', themeLayerColor, 'auto')
    };
    store.commit("getMapLayers", this.themeLayerInfo)
    map.overlayers["themerange"] = themeLayer
    map.overlayerInfos["themerange"] = this.themeLayerInfo

    sgisLayerBase.setOverLayers(this.themeLayerInfo);
    // //设置高亮图层提示
    // this.addFeatures(data.datas[0].values,themeLayer,map);
    return this.themeLayerInfo;
  },
  addFeatures(values, layer, map) {
    let valueTemp = {};
    let regioninfos = [];
    for (let i = 0; i < values.length; i++) {
      // 每一百个区划叠加一次，不一次性查询出来，村的边界数据太大
      let regioncode = values[i].regioncode;
      let value = values[i].value;
      let regiontype = values[i].regiontype;
      valueTemp[regioncode] = value;
      let regionInfo = {
        regioncode: regioncode,
        regiontype: regiontype
      };
      regioninfos.push(regionInfo);
      if (i > 0 && i % 100 === 0) {
        this.queryFeatures(valueTemp, regioninfos, layer, map);
        valueTemp = {};
        regioninfos = [];
      }
    }
    if (valueTemp !== null && !$.isEmptyObject(valueTemp)) {
      this.queryFeatures(valueTemp, regioninfos, layer, map);
    }
  },
  queryFeatures(data, regioninfos, themeLayer, map) {
    let that = this;
    let regiontype = regioninfos[0].regiontype;
    sgisSpatialQuery.spatialQueryUtil.getFeaturesByRegionCodes(
      regioninfos,
      regiontype,
      (serviceResult) => {
        that.callbackLayer();//一切执行完毕，才能执行回掉
        let result = serviceResult.result;
        if (result && result.features) {
          let features = result.features;
          // themeLayer.addFeatures();
          // 重新构造一下features
          for (let i = 0; i < features.features.length; i++) {
            let code = features.features[i].properties.QH_CODE;
            features.features[i].properties["value"] = data[code];
          }
          map.easeTo({
            pitch: 60,
            bearing: 0
          })
          map.addLayer(themeLayer)
          themeLayer.canvas.getContext("webgl2", { preserveDrawingBuffer: true })
          themeLayer.setData(features.features)
        }
      }
    );
  },
  setCustomColor(layer, colorParam) {
    let currStyleGroups = layer.styleGroups;
    /**
     * 判断颜色长度是否变化是否需要重新分段，
     * 1、如果分段数不变则直接调整颜色，重绘图层就可以
     * 2、如果分段数目发生改变则需要重新调整数据分段
     */
    const len = colorParam.colors.length;
    this.options.colors = colorParam.colors;
    if (currStyleGroups.length === len) {
      currStyleGroups = layer.styleGroups;
      for (let i = 0; i < currStyleGroups.length; i++) {
        currStyleGroups[i].style.color = colorParam.colors[i];
      }
    } else {
      // 重新调整分段数目，获取新的styleGroups
      let dataTemp = layer.options.currdata.all_segment_values;
      let segment_values_temp = dataAnalysis.themerange.getSegmentByDataArr(
        dataTemp,
        len
      ); // 这个地方要根据data重新获取
      layer.options.currdata.segment_values = segment_values_temp;
      currStyleGroups = layer.getStyleGroups(segment_values_temp);
    }
    this.options.refreshStyles(currStyleGroups, layer);
    this.options.calgraph(layer.layerId, layer.styleGroups, 'auto'); // 更新图例
  },
  hexToRgb(hex) {
    if (hex == "transparent") {
      return [0, 0, 0]
    }
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? [
      parseInt(result[1], 16),
      parseInt(result[2], 16),
      parseInt(result[3], 16)] : null;
  },
  /**
 * 刷新图层样式
 */
  refreshStyles(styleGroups, layer) {
    layer.styleGroups = styleGroups;
    layer.options.styleGroups = styleGroups
    layer.update();
  },
  /**
   * 设置图层可见性
   */
  setVisible(visible) {
    if (this.canvas) {
      this.canvas.style.visibility = visible;
    }
  },
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this.canvas);
  },
  getStyleGroups(segment_values) {
    let color = ["FEE5D9", "FCAE91", "FB6A4A", "DE2D26", "A50F15"];
    if (this.options && this.options.colors) {
      color = [];
      for (const item of this.options.colors) {
        const value = item.slice(1);
        color.push(value);
      }
    }

    // if (this.colors.length > 0) {
    //   color = this.colors[0];
    //   this.colors.splice(0, 1);
    // }
    let styleGroups = [];
    /**
     * 前后端分别用 -999999999999999999999999999   999999999999999999999999999
     * 保证覆盖到所有的值
     */
    for (let i = 0; i < segment_values.length; i++) {
      let style = {
        start: i === 0 ? -999999999999999999999999999 : parseInt(segment_values[i - 1]),
        end: i === segment_values.length - 1 ?
          999999999999999999999999999 : parseInt(segment_values[i]),
        style: {
          color: i === 0 ? getLightColor("#" + color[0], 0.5) : "#" + color[i - 1]
        }
      };
      styleGroups.push(style);
    }
    //hex颜色转rgb颜色
    function HexToRgb(str) {
      var r = /^\#?[0-9A-F]{6}$/;
      //test方法检查在字符串中是否存在一个模式，如果存在则返回true，否则返回false
      if (!r.test(str)) return window.alert("输入错误的hex");
      //replace替换查找的到的字符串
      str = str.replace("#", "");
      //match得到查询数组
      var hxs = str.match(/../g);
      //alert('bf:'+hxs)
      for (var i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16);
      //alert(parseInt(80, 16))
      //console.log(hxs);
      return hxs;
    }
    //GRB颜色转Hex颜色
    function RgbToHex(a, b, c) {
      var r = /^\d{1,3}$/;
      if (!r.test(a) || !r.test(b) || !r.test(c)) return window.alert("输入错误的rgb颜色值");
      var hexs = [a.toString(16), b.toString(16), c.toString(16)];
      for (var i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = "0" + hexs[i];
      return "#" + hexs.join("");
    }
    function getLightColor(color, level) {
      var r = /^\#?[0-9A-F]{6}$/;
      if (!r.test(color)) return window.alert("输入错误的hex颜色值");
      var rgbc = HexToRgb(color);
      for (var i = 0; i < 3; i++) rgbc[i] = Math.floor((255 - rgbc[i]) * level + rgbc[i]);
      return RgbToHex(rgbc[0], rgbc[1], rgbc[2]);
    }
    return styleGroups;
  },
  // 循环去取颜色，防止两次出图时颜色一样
  /* *设置图层透明度 */
  setOpacity(opacity) {
  },
  /* *图例样式计算 */
  calgraph(layerId, styleGroup, auto) {
    let html = `
     <div class="${layerId} chart_item" style='padding:6px;'>
        <ul style='padding:0;margin:0'>
    `;
    for (const key in styleGroup) {
      const item = styleGroup[key];
      html += `<li style='list-style:none;padding:5px 0;display:${item.start == item.end || item.end == 0 ? 'none' : 'block'}'>`;
      if (key === "0") {
        html += `<div style='display:flex;align-items: center;'><div style='display:inline-block;width:10px;height:10px;background:${item.style.color}'>
        </div><p style="color:#fff">&nbsp;&nbsp;&nbsp;&nbsp;<&nbsp;${item.end}</p></div>`;
      } else if (key === styleGroup.length - 1 + "") {
        html += `<div style='display:flex;align-items: center;'><div style='display:inline-block;width:10px;height:10px;background:${item.style.color}'>
        </div><p style="color:#fff">&nbsp;&nbsp;&nbsp;&nbsp;&gt;&nbsp;${item.start == 0 ? store.state.macro.currentIdenThemanger : item.start}</p>`
          ;
      } else {
        html += `<div style='display:flex;align-items: center;'><div style='display:inline-block;width:10px;height:10px;background:${item.style.color}'>
        </div><p style="color:#fff"><span>&nbsp;&nbsp;&nbsp;&nbsp;${item.start}</span>
        &nbsp;-&nbsp;<span>${item.end}</span></p>`;
      }
      html += `</li>`;
    }
    html += `</ul>
     </div>`;
    if (auto === 'auto') {
      const layers = sgisLayerBase.overLayers;
      for (const key in layers) {
        if (layers[key].layerId === layerId) {
          layers[key].html = html;
        }
      }
    }
    return html;
  },
};
